#include "../inc/group_chat.h"

void *Send(void *arg)
{
    pthread_detach(pthread_self());
    int *cli_fd = (int *)arg;
    char msg[1000];

    while (1)
    {
        memset(msg, 0, 256);
        printf("请输入要发送给服务器的消息：");
        if (scanf("%s", msg) != 1)
        {
            perror("scanf ....");
            break;
        }

        if (write(*cli_fd, msg, strlen(msg)) == -1)
        {
            perror("writeS ...");
            pthread_exit((void *)-1);
        }
        if (strcmp(msg, EXIT_MASK) == 0)
        {
            // 开启主动退出标志位
            EXIT_1 = 1;
            break;
        }
    }

    pthread_exit((void *)0);
}

void *Recv(void *arg)
{
    int *cli_fd = (int *)arg;

    char msg[1000];

    pthread_detach(pthread_self());

    while (1)
    {
        memset(msg, 0, 1000);

        if (read(*cli_fd, msg, sizeof(msg)) == -1)
        {
            perror("readR ...");
            pthread_exit((void *)-1);
        }
        if (strcmp(msg, EXIT_MASK) == 0)
        {
            printf("服务器即将关闭，当前客户端即将退出！\n");
            // EXIT_2 = 1;
            // close(STDIN_FILENO);//关闭标准输入
            break;
        }
        printf("\n%s\n", msg);
    }

    pthread_exit((void *)0);
}

bool Broadcast_Task(int *cli_fd)
{
    if (write(*cli_fd, WE_CHAT, strlen(WE_CHAT)) == -1)
    {
        perror("writeB ...");
        return false;
    }

    // 创建两条线程 --- 一条发送消息 一条读取消息
    pthread_t s_id, r_id;
    if (pthread_create(&s_id, NULL, Send, (void *)cli_fd) != 0)
    {
        perror("pthread_create ...");
        return -1;
    }

    if (pthread_create(&r_id, NULL, Recv, (void *)cli_fd) != 0)
    {
        perror("pthread_create ...");
        return -1;
    }

    while (1)
    {
        if (EXIT_1 == 1)
        {
            if (pthread_cancel(r_id) != 0) // 取消发送消息的线程
            {
                perror("pthread_cancel ... ");
                return -1;
            }
            EXIT_1 = 0;
            break;
        }
        sleep(1);
    }
    return true;
}
